<template>
  <div>
    <h3>德育教育</h3>
    <div class="body">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row style="margin-bottom: 20px;" :gutter="10" type="flex" justify="space-between">
            <el-col :span="4">
              <el-input v-model="searchForm.name" size="small" style="width: 80%;" suffix-icon="el-icon-view"
                placeholder="输入文档标题"></el-input>
            </el-col>
            <el-col :span="5">
              <el-select v-model="searchForm.docClassItemTypeId" size="small" collapse-tags filterable clearable
                placeholder="选择文档类型">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_doc_class_item_type" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select v-model="searchForm.sportId" size="small" collapse-tags filterable clearable
                placeholder="选择队组">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select v-model="searchForm.schoolGradeClassId" size="small" collapse-tags filterable clearable
                placeholder="选择班级">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_grade_class" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select v-model="searchForm.empId" size="small" collapse-tags filterable clearable placeholder="选择撰写者">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_emp" :key="index">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="6">
              <div style="display: flex;">
                <el-button type="success" icon="el-icon-plus" size="small" @click="insertMoralityEducation">新增
                </el-button>
                <el-button-group style="display: flex;">
                  <el-button type="success" icon="el-icon-printer" size="medium" @click="exportData">打印或导出</el-button>
                  <el-button type="success" size="medium" @click="exportSelectEvent"> {{checkText}} <i
                      class="el-icon-document-checked"></i></el-button>
                </el-button-group>
              </div>
            </el-col>
            <el-col :span="8">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="center" unlink-panels
                style="width: 70%;" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="5">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row
        highlight-current-row resizable :loading="loading" :data="dataList" @sort-change="sortChange"
        :export-config="{}">
        <vxe-column field="checkbox" type="checkbox" width="60"></vxe-column>
        <vxe-table-column field="name" title="文档标题" sortable min-width="250"></vxe-table-column>
        <vxe-table-column field="docClassItemType" title="文档类型" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="队组" sortable></vxe-table-column>
        <vxe-table-column field="schoolGradeClass" title="班级" sortable></vxe-table-column>
        <vxe-table-column field="emp" title="撰写者" sortable></vxe-table-column>
        <vxe-table-column field="createDate" title="创建日期" sortable></vxe-table-column>
        <vxe-table-column field="openDate" title="开始日期" sortable></vxe-table-column>
        <vxe-table-column field="closeDate" title="截止日期" sortable></vxe-table-column>
        <vxe-table-column field="status" title="状态" sortable width="70"></vxe-table-column>
        <vxe-table-column field="" title="操作" width="180">
          <template #default="{ row }">
            <el-button-group>
              <el-button @click="printModalShow(row)" type="primary" size="mini" icon="el-icon-view"></el-button>
              <el-button @click="planEdit(row)" type="primary" size="mini" icon="el-icon-edit"></el-button>
              <el-button @click="planDelete(row)" type="primary" size="mini" icon="el-icon-delete"></el-button>
            </el-button-group>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
        :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
        @page-change="handlePageChange">
      </vxe-pager>
      <!-- 单个打印预览 -->
      <vxe-modal v-model="printModal" title="预览" height="800" show-zoom resize width="600" show-footer>
        <template #default>
          <otherPlanPrint id="myPrint" :previewData="previewData" :docClassId="currentDocClassId" />
        </template>
        <template #footer>
          <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
          <el-button @click="downloadWord" type="primary" icon="iconfont icon-word1" size="mini"> 导出word</el-button>
        </template>
      </vxe-modal>
      <!-- 全部打印预览导出 -->
      <vxe-modal v-model="printWordModal" title="预览" height="800" show-zoom resize width="600" show-footer>
        <template #default>
          <planWordPrint id="myPrint" :docDataWord="docDataWord" />
        </template>
        <template #footer>
          <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
          <el-button @click="downloadWord" type="primary" icon="iconfont icon-word1" size="mini"> 导出word</el-button>
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

<script>
  import {
    moralityEducation,
    allType,
    plan_doc_delete,
    selectMoralityEducation,
    batchPrint
  } from '@/api/plan.js'
  import {
    currentRoleEmployee,
    sport_by_org,
    sport_item,
    grade_class,
    doc_class_item_type
  } from '@/api/dict.js'
  import otherPlanPrint from "@/components/print/otherPlanPrint.vue"
  import weekPlanPrint from "@/components/print/weekPlanPrint.vue"
  import planWordPrint from '@/components/print/planWordPrint.vue'
  import htmlDocx from 'html-docx-js/dist/html-docx';
  import saveAs from 'file-saver';
  export default {
    components: {
      otherPlanPrint,
      weekPlanPrint,
      planWordPrint
    },
    props: ['docClassId'],
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_emp: {},
        dict_sport: {},
        dict_sportItem: {},
        dict_doc_class_item_type: {},
        dict_grade_class: {},
        printModal: false,
        previewData: {},
        currentDocClassId: null,
        searchForm: {
          docClassItemTypeId: null,
          name: null,
          empId: null,
          sportId: null,
          schoolGradeClassId: null,
          beginDate: null,
          endDate: null,
        },
        doubleDate: null,
        printWordModal: false,
        search: false,
        checkText: '选择打印',
        currentRow: {},
      }
    },
    created() {
      this.init_dict().then(() => {
        this.getPlanList()
      })
    },
    computed: {
      docmentVisibility() {
        return this.$store.state.app.docmentVisibility;
      },
    },
    watch: {
      filterName(val) {
        if (!val) {
          this.page = {
            currentPage: 1,
            pageSize: 10,
            totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      },
      docmentVisibility(newVal) {
        if (!newVal) return;
        this.getPlanList()
      },
    },
    methods: {
      exportData() {
        this.getDocDataIdAll()
      },
      exportSelectEvent() {
        if (this.checkText == '选择打印') {
          this.checkText = '取消选择'
          this.$refs.XTable.showColumn(this.$refs.XTable.getColumnByField('checkbox'))
        } else {
          this.checkText = '选择打印'
          this.$refs.XTable.clearCheckboxRow()
          this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
        }
      },
      getDocDataIdAll() {
        let docDataIdArr = []
        let data = this.$refs.XTable.getCheckboxRecords()
        if (data.length == 0) {
          this.defaultDataList.forEach(item => {
            docDataIdArr.push(item.docDataId)
          })
        } else {
          data.forEach(item => {
            docDataIdArr.push(item.docDataId)
          })
        }
        batchPrint({
          docDataIds: docDataIdArr.join(',')
        }).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.docDataWord = res.data.reverse()
            this.printWordModal = true
          } else {
            this.$message.error(res.data)
          }
        })
      },
      insertMoralityEducation() {
        this.$router.push('/plan/viewMorality')
      },
      searchSubmit() {
        let data = {}
        if (this.searchForm.docClassItemTypeId) data.docClassItemTypeId = this.searchForm.docClassItemTypeId
        if (this.searchForm.empId) data.empId = this.searchForm.empId
        if (this.searchForm.name) data.name = this.searchForm.name
        if (this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if (this.searchForm.schoolGradeClassId) data.schoolGradeClassId = this.searchForm.schoolGradeClassId
        if (this.doubleDate) {
          data.beginDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        selectMoralityEducation(data).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          docClassItemTypeId: null,
          name: null,
          empId: null,
          sportId: null,
          schoolGradeClassId: null,
          beginDate: null,
          endDate: null,
        }
        this.doubleDate = null
        this.getPlanList()
      },
      planDelete(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          plan_doc_delete({
            docDataId: row.docDataId
          }).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功！')
              this.getPlanList()
            } else {
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      planEdit(row) {
        const {
          href
        } = this.$router.resolve({
          path: '/plan/viewMorality',
          query: {
            docDataId: row.docDataId
          }
        });
        window.open(href, '_blank');
      },
      downloadWord() {
        let data = this.$refs.XTable.getCheckboxRecords()
        let name = data.length != 0 ? data[0].name : this.currentRow.name
        const divEl = document.getElementById('myPrint')
        this.page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${divEl.innerHTML}</body></html>`
        const converted = htmlDocx.asBlob(this.page);
        // 用 FielSaver.js里的保存方法 进行输出
        saveAs(converted, name + '.docx');
      },
      printEvent() {
        const divEl = document.getElementById('myPrint')
        this.$XPrint({
          sheetName: '',
          content: divEl.innerHTML
        })
      },
      printModalShow(row) {
        this.currentRow = row
        this.currentDocClassId = row.docClassId
        allType({
          docDataId: row.docDataId,
          docClassId: row.docClassId
        }).then(res => {
          if (res.code === 200) {
            this.previewData = res.data
            this.printModal = true
          } else {
            this.$message.error(res.message)
          }
        })
      },
      getPlanList() {
        moralityEducation(this.docClassId).then(res => {
          if (res.code === 200) {
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
            this.$message.error(res.message)
          }
        }).then(() => {
          this.findList()
          this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
        })
      },
      init_data(data) {
        if (data.length == 0) return
        data.forEach(item => {
          item.emp = this.dict_emp[item.empId]
          item.docClassItemType = this.dict_doc_class_item_type[item.docClassItemTypeId]
          item.sport = this.dict_sport[item.sportId]
          item.schoolGradeClass = this.dict_grade_class[item.schoolGradeClassId]
          item.createDate = this.$moment(item.createDate).format('YYYY-MM-DD')
          item.closeDate = this.$moment(item.closeDate).format('YYYY-MM-DD')
          item.openDate = this.$moment(item.openDate).format('YYYY-MM-DD')
          item.status = item.statusId == 1 ? "正式" : "草稿"
          if (item.memo) {
            let arr = item.memo.split(',')
            let memoArr = []
            arr.forEach(memo => {
              memoArr.push(this.dict_emp[memo])
            })
            item.memoName = memoArr.join(',')
          }
        })
        if (data[0]) {
          this.searchProps = Object.keys(data[0])
        }
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          currentRoleEmployee().then(res => {
            this.dict_emp = res
            sport_by_org().then(res => {
              this.dict_sport = res
            })
            sport_item().then(res => {
              this.dict_sportItem = res
            })
            doc_class_item_type({
              docClassTypeId: 2
            }).then(res => {
              this.dict_doc_class_item_type = res
            })
            grade_class().then(res => {
              this.dict_grade_class = res
              resolve()
            })
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.dataList.length,
            totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
        }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        if (!this.search) {
          this.page.pageSize = this.defaultDataList.length
          this.findList()
        } else {
          this.page.pageSize = this.dataList.length
        }
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if (this.insertSuccess) {
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult / this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length - 1])
            this.insertSuccess = false
          } else {
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .body {
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
